<template>
    <div v-if="visible  || isShow" class="modal-setPwd">
        <div class="modal">
            <!-- <div class="close" @click="isVerifyEmail = false"></div> -->
            <div class="modal-header">
                <h3>{{$t('bind_email')}}</h3>
            </div>
            <p>{{ $t('send_email') }}</p>
            <div class="verification-code">
                <input
                    v-for="(digit, index) in digits"
                    :key="index"
                    type="text"
                    maxlength="1"
                    v-model="digits[index]"
                    @input="handleInput($event, index)"
                    @keydown.delete="handleBackspace(index)"
                    class="verification-input"
                    :id="`input-${index}`"
                />
            </div>
            <!-- <el-input ref="codeRef" v-model="code" type="text" style="margin-top: 10px;height: 36px;" :placeholder="$t('Verification_code')"></el-input> -->
            <el-button style="margin-top: 20px;" type="primary"  @click="save_bind">{{ $t('confirm') }}</el-button>
            <span v-show="isDisabled" :class="{filter:isDisabled}" class="resend" @click="send_code">{{ $t('Resend') }}<span>({{countNum}}s)</span></span>
            <span v-show="!isDisabled" class="resend" @click="send_code('reload')">{{ $t('send_code') }}</span>
            <span class="login_out" @click="signOut">{{ $t('login_out') }}</span>
        </div>
    </div>
</template>

<script setup>
import { useUserInfoStore } from '@/store/modules/user_info/index';
import { useI18n } from 'vue-i18n';
import axios from '@/utils/api'
import { useLoadingStore } from '@/store/modules/loading/index';
const loadingStore = useLoadingStore();

const props = defineProps(['visible'])
const isVisible = toRef(props, 'visible')
const isShow = ref(false)

const user_infoStore = useUserInfoStore();
const user_info = reactive(user_infoStore.userInfo)
const { locale } = useI18n();

let lang = ref('')
if(localStorage.getItem('lang') == 'en'){
    lang.value = 'en'
}else{
    lang.value = 'zh'
}
const signOut = () => {
    user_infoStore.clearUserinfo()
    user_infoStore.clearUserToken()
    user_infoStore.clearUserToken_expire()
    if(locale.value == 'zh'){
        ElMessage.success('登出成功')
    }else{
        ElMessage.success('Exit successful')
    }
    
    // console.log(user_infoStore.userToken);
    // router.replace('/home')
    window.location.reload()
}

const digits = ref(Array(6).fill(''))
const verificationCode = computed(() => digits.value.join(''));
// 处理输入事件，限制只能输入数字
const handleInput = (event, index) => {
    let inputValue = event.target.value.replace(/\D/g, '');
    digits.value[index] = inputValue;
    // 输入后跳转至下一个输入框
    if (inputValue !== '' && index < 5) {
        const nextInput = document.querySelector(`#input-${index + 1}`);
        if (nextInput) nextInput.focus();
    }

    // 当在最后一个输入框输入值时触发提交
    if (index === digits.value.length - 1 && checkAllFilled()) {
        save_bind();
    }
};
const handleBackspace = (index) => {
    // 当前输入框为空且不是第一个时，退格跳转至前一个
    if (digits.value[index] === '' && index > 0) {
        const prevInput = document.querySelector(`#input-${index - 1}`);
        if (prevInput) prevInput.focus();
    }
};
// 判断所有输入框是否都有值
const checkAllFilled = () => {
    return digits.value.every(digit => digit !== '');
};

const save_bind = async ()=>{
    const data = {
        id:user_info.id,
        code:verificationCode.value,
    }
    console.log(data,'data');
    const res = await axios.post('/activation_user',data)
    if(res.code == 200){
        if(lang.value == 'en'){
            ElMessage.success('Verification successful')
        }else{
            ElMessage.success('驗證成功')
        }
        user_info.status = 1
        setTimeout(() => {
            if(window.location.href.includes('/login')){
                window.location.href = '//'+window.location.hostname
            }else{
                window.location.reload() 
            }
            
        }, 1000);

    }else if(res.code == 60011){
        if(lang.value == 'en'){
            ElMessage.error('Verification code error, please re-enter')
        }else{
            ElMessage.error(res.message)
        }
    }else if(res.code == 6001){
        if(lang.value == 'en'){
            ElMessage.error('Please enter the verification code')
        }else{
            ElMessage.error(res.message)
        }
    }else if(res.code == 60010){
        if(lang.value == 'en'){
            ElMessage.error('Please click to send the verification code first')
        }else{
            ElMessage.error(res.message)
        }
    }else{
        ElMessage.error(res.message)
    }
}


const isDisabled = ref(false)
const countNum = ref(60)
let regex = null
const validateInput = (input)=> {
    regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if(regex.test(input)){
        return true
    }else{
        if(lang.value == 'en'){
            ElMessage.error('Please fill in the correct email address or phone number');
        }else{
            ElMessage.error('請填寫正確的郵箱');
        }
        return false
    }
}

let countdownInterval;  // 用于存储计时器的ID

const send_code = async (type) => {
    if(type == 'send' && countdownInterval){
       return
    }
    if (validateInput(user_info.username)) {
        if (type == 'reload') {
            loadingStore.startLoading();
        }
        isDisabled.value = true;

        nextTick(() => {
            const nextInput = document.querySelector(`#input-0`);
            if (nextInput) nextInput.focus();
        });

        const res = await axios.post('/send_email', { email: user_info.username });
        loadingStore.stopLoading();

        if (res.code == 200) {
            if (type == 'reload') { // 刷新页面进来的时候
                if (lang.value == 'en') {
                    ElMessage.success('Verification code sent successfully');
                } else {
                    ElMessage.success('驗證碼發送成功');
                }
            }

            // 获取当前时间戳
            const currentTimestamp = Date.now();
            const countdownEndTimestamp = currentTimestamp + 60 * 1000; // 60秒后

            // 保存倒计时结束时间戳到 localStorage
            localStorage.setItem('countdownEndTimestamp', countdownEndTimestamp);

            // 启动倒计时
            countdownInterval = setInterval(() => {
                const remainingTime = Math.max(0, countdownEndTimestamp - Date.now()); // 计算剩余时间

                countNum.value = Math.floor(remainingTime / 1000); // 更新倒计时秒数

                // 如果剩余时间为 0，停止倒计时
                if (remainingTime === 0) {
                    clearInterval(countdownInterval);
                    isDisabled.value = false;
                    countNum.value = 60;
                    localStorage.removeItem('countdownEndTimestamp');  // 倒计时结束后移除存储的时间戳
                }
            }, 1000);
        }
    }
};


onMounted(() => {
    // 获取倒计时结束的时间戳
    const countdownEndTimestamp = parseInt(localStorage.getItem('countdownEndTimestamp'));

    if (countdownEndTimestamp) {
        // 计算剩余时间
        const remainingTime = Math.max(0, countdownEndTimestamp - Date.now()); // 剩余时间（毫秒）

        if (remainingTime > 0) {
            countNum.value = Math.floor(remainingTime / 1000); // 更新倒计时秒数
            isDisabled.value = true; // 倒计时进行中时禁用按钮

            // 恢复倒计时
            countdownInterval = setInterval(() => {
                const remainingTime = Math.max(0, countdownEndTimestamp - Date.now()); // 计算剩余时间

                countNum.value = Math.floor(remainingTime / 1000); // 更新倒计时秒数

                // 如果剩余时间为 0，停止倒计时
                if (remainingTime === 0) {
                    clearInterval(countdownInterval);
                    isDisabled.value = false;  // 倒计时结束后恢复按钮
                    localStorage.removeItem('countdownEndTimestamp');  // 倒计时结束后移除存储的时间戳
                }
            }, 1000);
        }
    }

    // 检查用户状态
    if (user_info.status == 3) {
        isShow.value = true;
        if (!isDisabled.value) {
            send_code('reload');
        }
        nextTick(() => {
            const prevInput = document.querySelector(`#input-0`);
            if (prevInput) prevInput.focus();
        });
    }
});

// 在组件销毁时清除定时器
watchEffect(() => {
    console.log('组件销毁');
    
    if (countdownInterval) {
        clearInterval(countdownInterval);  // 清除倒计时定时器
    }
});

watch(isVisible,(newV) => {
    if (newV) {
        isShow.value = true;
        if (!isDisabled.value) {
            send_code('reload');
        }
        nextTick(() => {
            const prevInput = document.querySelector(`#input-0`);
            if (prevInput) prevInput.focus();
        });
    }
});



defineExpose({
    send_code,
});
</script>

<style lang="less" scoped>
.modal-setPwd {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2001;
    
    input{
        
        text-align: left;
    }
    @media (max-height: 400px) {
        .modal-content{
            display: flex;
        }
        .img_box{
            height: 383px;
            overflow: hidden;
            border-radius: 12px 0 0 12px;
            // background: linear-gradient(to bottom right, #f9f9f9, #ffffff);
            img{
                // position: relative;
                // top: 0;
                // transform: translateY(-50%);
                border-radius: 12px 0 0 12px;
            }
        }
    }
    @media (min-height: 401px) {
        .img_box{
            height: 250px;
            width: 393px;
            img{
                border-radius: 12px 12px 0 0;
            }
        }
    }

    .modal {
        background: linear-gradient(to bottom right, #f9f9f9, #ffffff);
        padding: 20px;
        border-radius: 12px;
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
        width: 320px;
        text-align: center;
        position: relative;
        animation: popIn 0.3s ease-out;
        .emailBox{
            display: flex;
            .inp{
                flex: 0.75;
                margin-left: 0;
                height: 35px;
            }
            .btn{
                flex: 0.2;
                margin-right: 0;
                height: 35px;
            }
        }
        p{
            color: #676767;
            font-size: 13px;
            margin-bottom: 15px;
        }
        .resend{
            color: #007dff;
            cursor: pointer;
            position: absolute;
            right: 22px;
            bottom: 27px;
            font-size: 14px;
        }
        .resend:hover{
            color: rgba(#007dff,.8);
        }
        .filter{
            filter: grayscale(1);
            pointer-events: none;
        }
    }

    @keyframes popIn {
        0% {
            transform: scale(0.9);
            opacity: 0;
        }

        100% {
            transform: scale(1);
            opacity: 1;
        }
    }

    .modal-header {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 10px;
        flex-direction: column;
        p{
            font-size: 13px;
            margin-top: 5px;
            color: #7f7f7f;
        }
    }

    .modal-header h3 {
        margin: 0;
        font-size: 24px;
        color: #3c4043;
        font-family: 'Roboto', sans-serif;
    }

    .close-button1 {
        background: none;
        border: none;
        font-size: 28px;
        color: #9aa0a6;
        cursor: pointer;
        transition: color 0.3s ease;
        position: absolute;
        right: 20px;
        top: 5px;
    }

    .close-button1:hover {
        color: #1a73e8;
    }

    .verification-code {
        display: flex;
        justify-content: center;
        gap: 10px;
    }

    .verification-input {
        width: 40px;
        height: 40px;
        text-align: center;
        font-size: 24px;
        border: 2px solid #ccc;
        border-radius: 5px;
        outline: none;
        transition: all .3s;
    }

    .verification-input:focus {
        border-color: #79bbff; /* 聚焦时的边框颜色 */
    }
    .login_out{
		position: absolute;
		left: 22px;
		bottom: 27px;
        font-size: 14px;
        color: #474747;
        cursor: pointer;
	}
}
</style>